import { Entity, GameMode, world } from "@minecraft/server";
import { GameComponent } from "@sapi-game/gameComponent";
import { EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { BlockedTeamColorMap, BlockedTeamData } from "../interface";
import { BlockedInCombatPlayer } from "../player";
import { BlockedMainState } from "../states/mainState";

export class BlockedInCombatRespawn extends GameComponent<BlockedMainState> {
    override onAttach(): void {
        this.subscribe(world.afterEvents.entityDie, (event) => {
            const deadEntity = event.deadEntity;
            if (deadEntity.typeId !== EntityTypeIds.Player) return;

            const result = this.context.groupSet.findById(deadEntity.id);
            if (!result) return;

            const { player, group } = result;

            // 减少生命并处理观战模式
            if (player.live > 0) {
                player.live--;
            }
            if (player.live <= 0) {
                player.player?.setGameMode(GameMode.Spectator);
            }

            this.broadcastDeathMessage(
                player,
                group.data,
                event.damageSource.damagingEntity
            );
        });
    }

    private broadcastDeathMessage(
        player: BlockedInCombatPlayer,
        teamData: BlockedTeamData,
        source?: Entity
    ) {
        const killerName = this.getKillerName(source);

        const playerName = this.buildColorerName(teamData, player);
        const message = killerName
            ? `${playerName} §r 被 ${killerName} §r 杀死了 (剩余 ${player.live} 命)`
            : `${playerName} §r 去世了 (剩余 ${player.live} 命)`;

        this.context.groupSet.sendMessage(message);
    }

    private getKillerName(source?: Entity): string | undefined {
        if (!source || source.typeId !== EntityTypeIds.Player) return undefined;

        const result = this.context.groupSet.findById(source.id);
        if (!result) return undefined;

        return this.buildColorerName(result.group.data, result.player);
    }

    private buildColorerName(
        team: BlockedTeamData,
        player: BlockedInCombatPlayer
    ) {
        return `${BlockedTeamColorMap[team.color].color}${player.name}`;
    }
}
